package tech.aistar.day10.plus;

import tech.aistar.day09.homework.Purcase;

/**
 * 本类用来演示: ++ -- 不是原子性操作
 *             JMM
 *
 * @author: success
 * @date: 2022/8/1 10:17 上午
 */
public class PlusDemo implements Runnable{//共享资源
    //实例变量
    private int i;

    @Override
    public void run() {
        for (int j = 0; j < 100000; j++) {
            add();
        }
        System.out.println(Thread.currentThread().getName()+":"+i);
    }

    //synchronized - 同步代码 - 只能由一个线程进去执行.
    //线程必须要抢到"锁"资源才能进入.但是会先清空本地缓存.

    //Thread-0:161937
    //Thread-1:200000

    public synchronized void add(){
        i++;
        //...
        //...
    }
}
class PlusDemoTest{
    public static void main(String[] args) {
        Runnable r = new PlusDemo();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);

        t1.start();
        t2.start();
    }
}
